from django.shortcuts import render
from rest_framework.views import APIView

from apps.users.models import User
from . models import Spit
from django.db import transaction
from django_redis import get_redis_connection
from .serializers import SpitReleaseModelSerializer
from rest_framework.response import Response
from .serializers import SpitListSerializer
from rest_framework.generics import ListAPIView
# Create your views here.


class SpitReleaseView(APIView):
    # 获取吐槽列表
    def get(self,request):
        spits = Spit.objects.all()
        # 创建redis连接对象
        redis_conn = get_redis_connection()

        # 判断用户是否登录 显示收藏信息
        if request.user.is_authenticated:

            for spit in spits:
                collected = redis_conn.hget('collected_%d' % request.user.id, spit.id)
                if collected is None:
                    collected = None
                elif int(collected) == 0:
                    # 转换成int类型
                    collected = False
                elif int(collected) == 1:
                    collected = True

                hasthumbup = redis_conn.hget('hasthumbup_%d' % request.user.id,spit.id)

                if hasthumbup is None:
                    hasthumbup = None
                elif int(hasthumbup) == 0:
                    hasthumbup = False
                elif int(hasthumbup) == 1:
                    hasthumbup = True

                spit.collected = collected
                spit.hasthumbup = hasthumbup

            ser = SpitReleaseModelSerializer(spits,many=True)
            print(ser.data)
            return Response(ser.data)
        else:
            ser = SpitReleaseModelSerializer(spits,many=True)
            return Response(ser.data)

    # # 发布吐槽
    # def post(self,request):
    #
    #     # 接受数据
    #     data = request.data
    #     with transaction.atomic():
    #         save_point = transaction.savepoint()
    #         spit = Spit.objects.create(**data)
    #
    #     # 指定系列化器
    #         ser = SpitReleaseModelSerializer(spit)
    #         transaction.savepoint_commit(save_point)
    #     return Response(ser.data)

    def post(self, request):
        # 接收数据
        data = request.data
        parent_id = data.get("parent")

        if parent_id:
            del data['parent']
            data["parent_id"] = parent_id
            print(data)
        spit = Spit.objects.create(**data)
        if spit.parent:
            spit.parent.comment += 1
            spit.parent.save()
        # 序列化
        ser = SpitReleaseModelSerializer(spit)
        #{'content': '333', 'parent_id': 1}
        return Response(ser.data)


class SpitDetailsView(APIView):
    '''吐槽详情'''
    def get(self,request,pk):

        queryset = Spit.objects.get(id=pk)
        ser = SpitReleaseModelSerializer(queryset)

        return Response(ser.data)


# 获取吐槽品论
class SpitParentView(APIView):

    def get(self,request,pk):

        spits = Spit.objects.filter(parent_id=pk)
        serializer = SpitListSerializer(spits,many=True)

        return Response(serializer.data)


# 收藏或取消收藏
class CollectView(APIView):

    def put(self,request,pk):

        # 判断是否登录
        if not request.user.is_authenticated:
            return Response(status=407)

        # 创建redis链接 点赞收藏存储在redis中 存储方式hash
        redis_conn = get_redis_connection('default')
        # 获取收藏的信息id
        data = redis_conn.hget('collected_%d' % request.user.id,pk)
        # 如果有id信息 表示取消收藏
        if data:
            redis_conn.hset('collected_%d' % request.user.id, pk,0)
            data_list = {'message':'取消成功','success':'true'}
            return Response(data=data_list,status=200)
        # 如果不存在 表示收藏
        else:
            redis_conn.hset('collected_%d' % request.user.id, pk,1)
            data_list = {'message':'收藏成功','success':'true'}
            return Response(data=data_list,status=200)


# 点赞或取消点赞
class LikeView(APIView):

    def put(self,request,pk):

        # 判断是否登录
        if not request.user.is_authenticated:
            return Response(status=407)

        # 创建redis链接 点赞存储到redis中
        redis_conn = get_redis_connection('default')
        # 获取点赞的id
        data = redis_conn.hget('hasthumbup_%d' % request.user.id,pk)
        # 判断是否存在 如果存在表示取消点赞
        if data:
            redis_conn.hset('hasthumbup_%d' % request.user.id, pk,0)
            data_list = {'message':'取消点赞','success':'true'}
            return Response(data=data_list,status=200)
        # 如果不存在 表示点赞
        else:
            redis_conn.hset('hasthumbup_%d' % request.user.id, pk,1)
            data_list = {'message':'点赞成功','success':'true'}
            return Response(data=data_list,status=200)